package com.weijian.controller;

import com.weijian.common.result.ApiResponse;
import com.weijian.dal.entity.Task;
import com.weijian.dal.enums.TaskStatus;
import com.weijian.service.AlgorithmExecutionService;
import com.weijian.service.TaskService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.Arrays;

/**
 * 算法执行接口
 */
@Tag(name = "算法执行", description = "匹配算法执行接口")
@RestController
@RequestMapping("/api/algorithm")
public class AlgorithmExecutionController {

    @Autowired
    private AlgorithmExecutionService algorithmExecutionService;

    @Autowired
    private TaskService taskService;

    /**
     * 执行匹配算法（异步）
     *
     * @param dataId 数据ID
     * @return 任务启动结果
     */
    @Operation(summary = "执行匹配算法（异步）")
    @PostMapping("/execute/async")
    public ApiResponse<String> executeMatchingAlgorithmAsync(@RequestParam Integer dataId) {
        // 检查是否有正在进行中的任务
        Task existingTask = taskService.lambdaQuery()
                .eq(Task::getDataId, dataId)
                .in(Task::getStatus, Arrays.asList(TaskStatus.PENDING, TaskStatus.RUNNING))
                .orderByDesc(Task::getCreatedAt)
                .last("LIMIT 1")
                .one();

        if (existingTask != null) {
            return ApiResponse.success("该批数据正在执行算法中，请勿重复执行，任务ID: " + existingTask.getTaskNo());
        }

        // 检查最近是否有成功的任务
        Task recentSuccessTask = taskService.lambdaQuery()
                .eq(Task::getDataId, dataId)
                .eq(Task::getStatus, TaskStatus.SUCCESS)
                .orderByDesc(Task::getUpdatedAt)
                .last("LIMIT 1")
                .one();

        if (recentSuccessTask != null) {
            return ApiResponse.success("该批数据近期已执行过算法，无需重复执行");
        }

        // 创建任务并关联上传的数据
        String taskNo = taskService.createTask(dataId);

        // 启动异步任务
        algorithmExecutionService.executeMatchingAlgorithmAsync(taskNo);

        // 返回任务ID
        return ApiResponse.success("算法执行任务已启动，任务ID: " + taskNo);
    }

    /**
     * SSE订阅任务状态
     *
     * @param taskId 任务ID
     * @return SseEmitter
     */
    @Operation(summary = "SSE订阅任务状态")
    @GetMapping(value = "/sse/status/{taskId}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter subscribeToTaskStatus(
            @Parameter(description = "任务ID") @PathVariable String taskId) {
        return taskService.registerTask(taskId);
    }
}